package service

import (
	"context"
	"fmt"
	"strconv"
	"teng-srv/basic/inits"
	__ "teng-srv/basic/proto"
	"teng-srv/handler/model"
)

type Server struct {
	__.UnimplementedStreamGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) VideoAdd(_ context.Context, in *__.VideoAddReq) (*__.VideoAddResp, error) {
	Video := model.Video{
		Name:  in.Name,
		Title: in.Title,
		Num:   int(in.Num),
		Like:  int(in.Like),
	}

	inits.DB.Debug().Create(&Video)
	return &__.VideoAddResp{
		Id: int64(Video.ID),
	}, nil
}

// 列表
func (s *Server) VideoList(_ context.Context, in *__.VideoListReq) (*__.VideoListResp, error) {
	var Videolist []model.Video
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize

	inits.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Find(&Videolist)

	var lists []*__.ReqList
	for _, i := range Videolist {
		list := __.ReqList{
			Name:  i.Name,
			Title: i.Title,
			Num:   int64(i.Num),
			Like:  int64(i.Like),
		}
		lists = append(lists, &list)
	}
	return &__.VideoListResp{
		List: lists,
	}, nil
}

// 会员列表
func (s *Server) MemberList(_ context.Context, in *__.MemberListReq) (*__.MemberListResp, error) {
	var MemberList []model.Member
	inits.DB.Debug().Find(&MemberList)

	var lists []*__.ReqMember
	for _, member := range MemberList {
		list := __.ReqMember{
			Right:  member.Right,
			Money:  strconv.Itoa(member.Money),
			Status: member.Status,
		}
		lists = append(lists, &list)
	}

	return &__.MemberListResp{
		List: lists,
	}, nil
}

// 续费提醒
func (s *Server) Member(_ context.Context, in *__.MemberReq) (*__.MemberResp, error) {

	var member model.Member
	inits.DB.Debug().Where("Money=?", in.Money).Find(&member)
	if member.Money == 0 {
		return nil, fmt.Errorf("会员余额小于0")
	}
	return &__.MemberResp{
		Id: int64(member.ID),
	}, nil
}

// 会员订阅
func (s *Server) VenueList(_ context.Context, in *__.VenueListReq) (*__.VenueListResp, error) {
	venue := model.Venue{
		Membername: in.Membername,
		Time:       in.Time,
		Title:      in.Title,
		Desc:       in.Desc,
	}

	//inits.DB.Debug().Find(&venue)
	//if in.Membername != "" {
	//	return nil, fmt.Errorf("会员已存在")
	//}
	inits.DB.Debug().Create(&venue)
	return &__.VenueListResp{
		Id: int64(venue.ID),
	}, nil
}

// 会员订阅记录
func (s *Server) VenueFind(_ context.Context, in *__.VenueFindReq) (*__.VenueFindResp, error) {
	var venuelist []model.Venue
	inits.DB.Debug().Find(&venuelist)

	var lists []*__.ReqFind
	for _, i2 := range venuelist {
		list := __.ReqFind{
			Membername: i2.Membername,
			Time:       i2.Time,
			Title:      i2.Title,
			Desc:       i2.Desc,
		}
		lists = append(lists, &list)
	}
	return &__.VenueFindResp{
		List: lists,
	}, nil
}
